#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include "sql.h"  

#define PORT 8080
#define BUFFER_SIZE 1024
#define MAX_CONNECTIONS 5
#define SERVER_DB_PATH "s_temper.db"

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    const char *ack = "ACK: Data received";
    
    // 初始化数据库
    if (sql_init_db(SERVER_DB_PATH) < 0) {
        fprintf(stderr, "服务器数据库初始化失败\n");
        return EXIT_FAILURE;
    }

    
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket creation failed");
        sql_close_db();
        exit(EXIT_FAILURE);
    }

    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt failed");
        sql_close_db();
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;  // 监听所有网络接口
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        sql_close_db();
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_fd, MAX_CONNECTIONS) < 0) {
        perror("listen failed");
        sql_close_db();
        exit(EXIT_FAILURE);
    }
    printf("Server listening on port %d...\n", PORT);

    while(1) {
        
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept failed");
            continue;  
        }
        printf("New client connected from %s:%d\n", 
               inet_ntoa(address.sin_addr), ntohs(address.sin_port));

        while(1) {
            ssize_t bytes_read = read(new_socket, buffer, BUFFER_SIZE);
            if (bytes_read <= 0) {
                if (bytes_read == 0) {
                    printf("Client disconnected\n");
                } else {
                    perror("read failed");
                }
                break;
            }
            
            buffer[bytes_read] = '\0';  // 确保字符串终止
            printf("Received sensor data: %s\n", buffer);
            
            // 解析数据并存入数据库
            SensorData sensor_data = {0};
            char timestamp[32] = {0};
            float temp = 0.0, humidity = 0.0;
            int temp_error = 0, humidity_error = 0;
            
            // 解析时间戳
            if (buffer[0] == '[') {
                sscanf(buffer, "[%31[^]]]", timestamp);
                strncpy(sensor_data.timestamp, timestamp, sizeof(sensor_data.timestamp));
            }
            
            // 解析温度数据
            char *temp_ptr = strstr(buffer, "Temperature: ");
            if (temp_ptr) {
                sscanf(temp_ptr, "Temperature: %f°C", &temp);
                sensor_data.temperature = temp;
            } else {
                temp_ptr = strstr(buffer, "Temperature error: ");
                if (temp_ptr) {
                    sscanf(temp_ptr, "Temperature error: %d", &temp_error);
                    sensor_data.temperature = -999;
                }
            }
            
            // 解析湿度数据
            char *humidity_ptr = strstr(buffer, "Humidity: ");
            if (humidity_ptr) {
                sscanf(humidity_ptr, "Humidity: %f%%", &humidity);
                sensor_data.humidity = humidity;
            } else {
                humidity_ptr = strstr(buffer, "Humidity error: ");
                if (humidity_ptr) {
                    sscanf(humidity_ptr, "Humidity error: %d", &humidity_error);
                    sensor_data.humidity = -999;  
                }
            }
            
            // 设置传感器ID（可以使用客户端IP或其他标识）
            snprintf(sensor_data.sensor_id, sizeof(sensor_data.sensor_id), 
                    "%s:%d", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
            
            
            printf("Parsed data:\n");
            printf("  Timestamp: %s\n", sensor_data.timestamp);
            if (temp_error) {
                printf("  Temperature error: %d\n", temp_error);
            } else {
                printf("  Temperature: %.2f°C\n", sensor_data.temperature);
            }
            if (humidity_error) {
                printf("  Humidity error: %d\n", humidity_error);
            } else {
                printf("  Humidity: %.1f%%\n", sensor_data.humidity);
            }
            
            // 将有效数据存入数据库
            if (!temp_error && !humidity_error) {
                int record_id = sql_insert_data(&sensor_data);
                if (record_id < 0) {
                    printf("Failed to insert data into database\n");
                } else {
                    printf("Data inserted into database with ID: %d\n", record_id);
                }
            }
            
            // 发送确认
            if (send(new_socket, ack, strlen(ack), 0) < 0) {
                perror("send failed");
                break;
            }
        }

        // 7. 关闭连接
        close(new_socket);
    }
    close(server_fd);
    sql_close_db();
    return 0;
}